import router from '@/router'
import store from './store'
import nprogress from 'nprogress'
import { asyncRoutes } from '@/router/index'
import 'nprogress/nprogress.css'
const whiteList = ['/login', '/404']
// 路由前置守卫
router.beforeEach(async(to, from, next) => {
  nprogress.start()
  const token = store.getters.token
  if (token) { // 身份鉴定
    if (to.path === '/login') {
      next('/')
      nprogress.done()
    } else {
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        const result = asyncRoutes.filter(item => {
          return roles.menus.includes(item.name)
        })
        router.addRoutes([...result, { path: '*', redirect: '/404', hidden: true }])
        store.commit('user/SET_ROUTER', result)
        next(to.path)
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      nprogress.done()
    }
  }
})
// 路由后置守卫
router.afterEach(() => {
  nprogress.done()
})
